/**
 * Created by henian.xu on 2018/8/1.
 *
 */
import Qs from 'qs';

class Comm {
    /**
     * 创建不重复Key
     * @returns {string}
     */
    getKey() {
        // const t  = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
        const t = 'xxxxxxxx';
        return t.replace(/[xy]/g, function(c) {
            const r = (Math.random() * 16) | 0;
            const v = c === 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }

    /**
     * 合并表单项
     * @param formModel
     * @param obj
     */
    formModelMerge(formModel, obj) {
        for (const key in formModel) {
            if (formModel.hasOwnProperty(key)) {
                let item = obj[key];
                if (typeof item === 'string') {
                    item = item.trim();
                }
                const isBooleanAnNumber = typeof item === 'boolean' || typeof item === 'number';
                if (
                    !isBooleanAnNumber &&
                    (!item || (Array.isArray(item) && !item.length) || JSON.stringify(item) === '{}')
                ) {
                    continue;
                }
                formModel[key] = item;
            }
        }
    }

    /**
     * 数值格式化
     * @param value
     * @param length
     * @returns {*}
     */
    filterNumber(value, length = 2) {
        if (isNaN(value)) {
            const nArr = (value + '').split('-');
            if (nArr.length === 1) return value;
            const rArr = [];
            nArr.forEach(item => {
                rArr.push(isNaN(item) ? item : +Number(item).toFixed(length));
            });
            return rArr.join('-');
        } else {
            return +Number(value).toFixed(length);
        }
    }

    // excel下载
    exportExcel(url, data) {
        let queryUrl = Qs.stringify(data);
        window.location.href = url + '?' + queryUrl;
    }

    //获取当前月份第一天
    getSysMonthFirstDayDate() {
        const date = new Date();
        let statDate = date.getFullYear() + '-' + (Array(2).join('0') + (date.getMonth() + 1)).slice(-2) + '-01';
        return statDate;
    }

    //获取当前年月日
    getSysDayDate() {
        const date = new Date();
        let statDate =
            date.getFullYear() +
            '-' +
            (Array(2).join('0') + (date.getMonth() + 1)).slice(-2) +
            '-' +
            (Array(2).join('0') + date.getDate()).slice(-2);
        return statDate;
    }

    //获取当年第一个月
    getSysYearFirstMonthDate() {
        const date = new Date();
        let statDate = date.getFullYear() + '-01';
        return statDate;
    }

    //获取当前年月
    getSysMonthDate() {
        const date = new Date();
        let statDate = date.getFullYear() + '-' + (Array(2).join('0') + (date.getMonth() + 1)).slice(-2);
        return statDate;
    }

    // 表单校验
    validateForm(forms, showFirstErrorField = true) {
        forms = forms.filter(form => form._isVue && form.validate);
        let callback,
            count = 0,
            len = forms.length,
            invalidFields = [],
            formsMap = {},
            resultValid = true;
        if (!forms.length) return Promise.resolve(true);
        const promise = new Promise((resolve, reject) => {
            callback = (valid, invalidFieldMap, _uid) => {
                if (!valid) resultValid = false;
                Object.keys(invalidFieldMap || {}).forEach(field => {
                    invalidFields.push(formsMap[_uid].fieldsMap[field]);
                });
                if (++count !== len) return;
                if (!resultValid) {
                    if (showFirstErrorField && invalidFields.length) {
                        invalidFields[0].scrollIntoView(true);
                    }
                    reject({ errorField: invalidFields });
                } else {
                    resolve(true);
                }
            };
        });
        forms.forEach(form => {
            formsMap[form._uid] = {
                fieldsMap: form.fields.reduce((prev, curr) => {
                    prev[curr.prop] = curr.$el;
                    return prev;
                }, {}),
            };
            form.validate((valid, invalidFieldMap) => {
                callback(valid, invalidFieldMap, form._uid);
            });
        });
        return promise;
    }
}

export default new Comm();
export { Comm };
